package com.taotao.sso.service.impl;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.manager.mapper.TbUserMapper;
import com.taotao.manager.pojo.TbUser;
import com.taotao.manager.pojo.TbUserExample;
import com.taotao.sso.service.UserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserRegisterServiceImpl implements UserRegisterService {
    @Autowired
    private TbUserMapper userMapper;

    @Override
    public TaotaoResult checkData(String param, Integer type) {
        //注入mapper
        //根据参数动态生成查询条件
        //调用mapper查询数据
        //如果查询到数据  --证明数据已存在,返回false
        //如果没查询到数据 --证明数据可用,返回true
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();

        if(type==1){
            //校验username
            criteria.andUsernameEqualTo(param);
        }else if(type==2){
            //校验phone
            criteria.andPhoneEqualTo(param);
        }else if(type==3){
            //校验email
            criteria.andEmailEqualTo(param);
        }else {
            //非法参数
            //return 非法
            return TaotaoResult.build(400, "非法的参数");
        }

        List<TbUser> list = userMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return TaotaoResult.ok(false);
        }
        return TaotaoResult.ok(true);
    }

    @Override
    public TaotaoResult register(TbUser user) {
        //注入mapper
        //校验数据  校验用户名和密码不能为空
        if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
            return TaotaoResult.build(400, "注册失败,请校验数据后再提交数据");
        }
        TaotaoResult taotaoResult1 = checkData(user.getUsername(), 1);
        if(!(Boolean) taotaoResult1.getData()){
            return TaotaoResult.build(400, "注册失败,请校验数据后再提交数据");
        }

        if (!StringUtils.isEmpty(user.getPhone())) {
            TaotaoResult taotaoResult2 = checkData(user.getPhone(), 2);
            if(!(Boolean) taotaoResult2.getData()){
                return TaotaoResult.build(400, "注册失败,请校验数据后再提交数据");
            }
        }

        if (!StringUtils.isEmpty(user.getEmail())) {
            TaotaoResult taotaoResult3 = checkData(user.getEmail(), 3);
            if(!(Boolean) taotaoResult3.getData()){
                return TaotaoResult.build(400, "注册失败,请校验数据后再提交数据");
            }
        }
        Date date = new Date();
        user.setCreated(date);
        user.setUpdated(date);
        String xpassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(xpassword);
        userMapper.insertSelective(user);
        return TaotaoResult.ok();
    }
}
